// static/user/js/modules/cart.js
class CartManager {
    constructor() {
        this.cartDrawer = document.getElementById('cartDrawer');
        this.cartList = document.getElementById('cartList');
        this.selectAllCheckbox = document.getElementById('selectAll');
        this.maskLayer = document.getElementById('globalMaskLayer');
        this.init();
    }

    async init() {
        this.bindEvents();
        await this.loadCart();
    }

    async loadCart() {
        try {
            const data = await fetchData(API.CART.LIST);
            this.renderCart(data);
            this.updateCartBadge(data.length);
            this.updateSelectedCount();
            this.calculateTotalAmount();
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    renderCart(items) {
        this.cartList.innerHTML = items.map(item => `
      <div class="cart-item" data-cart-id="${item.id}">
        <label class="cart-item__select">
          <input type="checkbox" ${item.selected ? 'checked' : ''}>
        </label>
        <img class="cart-item__image" src="${item.image || '/static/default-image.jpg'}">
        <div class="cart-item__content">
          <h4 class="cart-item__title">${item.name}</h4>
          <p class="cart-item__price">¥${item.price}/天</p>
          <div class="cart-item__actions">
            <div class="quantity-control">
              <button class="quantity-btn" data-action="remove">-</button>
              <input type="number" class="quantity-input" value="${item.quantity}" min="1">
              <button class="quantity-btn" data-action="add">+</button>
            </div>
            <button class="delete-btn" data-action="delete">删除</button>
          </div>
        </div>
      </div>
    `).join('');

        this.selectAllCheckbox.checked = items.every(item => item.selected);
    }

    bindEvents() {
        // 全局购物车按钮
        document.getElementById('cartButton').addEventListener('click', () => {
            this.openDrawer();
            this.loadCart();

        });

        // 关闭抽屉
        this.cartDrawer.querySelector('.cart-drawer__close-btn').addEventListener('click', this.closeDrawer);

        // 修改数量操作事件处理
        this.cartList.addEventListener('click', async (e) => {
            const btn = e.target.closest('button');
            if (!btn) return;

            const cartItem = btn.closest('.cart-item');
            const cartId = cartItem.dataset.cartId;
            let action = btn.dataset.action;
            const quantityInput = cartItem.querySelector('.quantity-input');

            try {
                // 处理减少操作
                if (action === 'remove') {
                    const currentQty = parseInt(quantityInput.value);
                    if (currentQty <= 1) {
                        action = 'delete'; // 自动切换为删除操作
                    }
                }

                await fetchData(API.CART.UPDATE, {
                    cartId,
                    type: action
                });

                // 如果删除成功则移除DOM节点
                if (action === 'delete') {
                    cartItem.remove();
                }

                await this.loadCart();
                this.calculateTotalAmount();
            } catch (error) {
                Alert.show(error.message, 'error');
            }
        });

        // 选中状态变更
        this.cartList.addEventListener('change', (e) => {
            if (e.target.type === 'checkbox') {
                this.updateSelectedItems();
                this.calculateTotalAmount();
                this.updateSelectedCount();
            }
        });

        // 全选操作
        this.selectAllCheckbox.addEventListener('change', () => {
            const checkboxes = this.cartList.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.selectAllCheckbox.checked;
            });
            this.updateSelectedItems();
            this.updateSelectedCount();
        });

        document.getElementById('checkoutBtn').addEventListener('click', () => {
            const selectedCount = this.cartList.querySelectorAll('input[type="checkbox"]:checked').length;
            if (selectedCount === 0) {
                Alert.show('请先选择要支付的器材', 'warning');
                return;
            }
            paymentManager.showPaymentModal();
        });

        this.cartDrawer.querySelector('.cart-drawer__close-btn').addEventListener('click', this.closeDrawer.bind(this));
        this.maskLayer.addEventListener('click', this.closeDrawer.bind(this));
    }

    // 更新选中数量显示
    updateSelectedCount() {
        const count = this.cartList.querySelectorAll('input[type="checkbox"]:checked').length;
        document.getElementById('selectedCount').textContent = `已选${count}件`;
    }

    /**
     * 计算总金额
     */
    calculateTotalAmount() {
        console.log('计算支付按钮文本文字');
        let total = 0;
        const selectedItems = this.cartList.querySelectorAll('input[type="checkbox"]:checked');

        selectedItems.forEach(item => {
            const cartItem = item.closest('.cart-item');
            const price = parseFloat(cartItem.querySelector('.cart-item__price').textContent.replace('¥', ''));
            const quantity = parseInt(cartItem.querySelector('.quantity-input').value);
            total += price * quantity * 7; // 7天租金
        });
        console.log('总金额：', total);
        document.getElementById('cart-total-amount').textContent = `¥${total.toFixed(2)}`;
        document.getElementById('checkoutBtn').dataset.total = total;
    }
    async updateSelectedItems() {
        const selectedItems = Array.from(this.cartList.querySelectorAll('input[type="checkbox"]:checked'))
            .map(checkbox => ({
                cartId: checkbox.closest('.cart-item').dataset.cartId,
                selected: checkbox.checked
            }));

        try {
            await fetchData(API.CART.SELECT, {
                cartSelectedDtoList: selectedItems
            });
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    updateCartBadge(count) {
        console.log('更新购物车徽章');
        document.getElementById('cartBadge').textContent = count;
    }

    // 修改后的关闭方法
    closeDrawer() {
        this.cartDrawer.classList.remove('cart-drawer--active');
        MaskLayer.hide();

        // 移除事件监听（安全移除）
        this.cartDrawer.querySelector('.cart-drawer__close-btn').removeEventListener('click', this.closeDrawer);
        this.maskLayer.removeEventListener('click', this.closeDrawer);
    }

    // 打开抽屉时重新绑定
    openDrawer() {
        MaskLayer.show();
        this.cartDrawer.classList.add('cart-drawer--active');
        this.bindCloseEvents();
    }

    bindCloseEvents() {
        this.cartDrawer.querySelector('.cart-drawer__close-btn').addEventListener('click', this.closeDrawer.bind(this));
        this.maskLayer.addEventListener('click', this.closeDrawer.bind(this));
    }

}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new CartManager();
});


// 新增Cart工具类
class Cart {
    static async addItem(productId) {
        try {
            await fetchData(API.CART.ADD, { productId })
            var cartManager = new CartManager();
            cartManager.loadCart();
            Alert.show('添加成功', 'success');
        } catch (error) {
            if (error.message.includes('登录')) {
                Alert.confirmWithCallback(error.message, () => {
                    window.location.href = '/login';
                }, '未登录提示');
            } else {
                Alert.show(error.message, 'error');
            }
        }
    }
}
window.Cart = Cart;